package com.login;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.dbcon.DBConnection;
import com.dbcon.MD5Crypt;
import com.util.Constant;
import com.util.Util;

public class UserRegister extends Thread {

	private String userName = null;
	private String userPass = null;

	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rst = null;

	public UserRegister(String userName, String pass) {
		this.userName = userName;
		this.userPass = pass;
		conn = DBConnection.getConnection();
	}

	public synchronized String regist() {
		String sql = "SELECT count(*) FROM daim_member WHERE rtrim(username)= ? ;";
		String msg = null;
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, userName);
			pstmt.executeQuery();
			rst = pstmt.getResultSet();
			rst.next();
			if (rst.getInt(1) > 0) {// user name has been used
				msg = Constant.CMD_CREATE_FAILED;
			} else {
				sql = "SELECT user_id_int FROM daim_user_id WHERE rtrim(name)=?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, "name");
				pstmt.executeQuery();
				rst = pstmt.getResultSet();
				rst.next();

				int user_id = rst.getInt(1);
				sql = "UPDATE daim_user_id SET user_id_int=?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, user_id + 1);
				pstmt.execute();

				String nowDate = Util.getNowDatetime();
				String dbPassword = MD5Crypt.crypt(this.userPass);
				sql = "INSERT INTO daim_member (user_id,username,pass,createdate,preaccount) VALUES(?,?,?,?,?)";
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, user_id);
				pstmt.setString(2, userName);
				pstmt.setString(3, dbPassword);
				pstmt.setString(4, nowDate);
				pstmt.setString(5, nowDate);
				pstmt.execute();
				msg = Constant.CMD_CREATE_SUCCESS;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rst != null) {
					rst.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return msg;
	}// end run()
}
